package org.conan.groupapp.system.service;

import java.util.HashSet;
import java.util.Set;

import org.conan.groupapp.system.entity.Authority;
import org.conan.groupapp.system.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 实现SpringSecurity的UserDetailsService接口,获取用户Detail信息
 * 
 * 
 */
public class UserDetailServiceImpl implements UserDetailsService {
	@Autowired
	@Qualifier("userServiceImpl")
	private IUserService iUserService;
	
	/**
	 * 
	 */
	@Override
	public UserDetails loadUserByUsername(String username) 
			throws UsernameNotFoundException,DataAccessException {
		User user = null;
		try {
			user = iUserService.selectUserByUsername(username);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (user == null) {
			throw new UsernameNotFoundException("用户" + username + " 不存在");
		}

		// 获取用户所有的权限
		Set<Authority> aList = null;;
		try {
			aList = iUserService.selectAuthoritiesByUsername(username);
		} catch (Exception e) {
			e.printStackTrace();
			throw new UsernameNotFoundException("iUserService.selectAuthoritiesByUsername() error");
		}

		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		for (Authority a : aList) {
			authSet.add(new GrantedAuthorityImpl(a.getAuthCode()));
		}
		
		user.setEnabled(true);
		user.setAccountNonExpired(true);
		user.setAccountNonLocked(true);
		user.setCredentialsNonExpired(true);
		user.setAuthorities(authSet);
		return user;
	}

	public IUserService getiUserService() {
		return iUserService;
	}

	public void setiUserService(IUserService iUserService) {
		this.iUserService = iUserService;
	}
	
	

}
